package com.qfedu.edu.stockservice.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qfedu.edu.bo.OrderShow;
import com.qfedu.edu.bo.QueueMessage;
import com.qfedu.edu.bo.ReduceStock;
import com.qfedu.edu.exception.BusinessException;
import com.qfedu.edu.manager.RedisManager;
import com.qfedu.edu.po.StockStorage;
import com.qfedu.edu.po.StockStorageHistory;
import com.qfedu.edu.result.ResponseCode;
import com.qfedu.edu.stockservice.mapper.StockStorageHistoryMapper;
import com.qfedu.edu.stockservice.mapper.StockStorageMapper;
import com.qfedu.edu.stockservice.service.StockStorageService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author xiaobobo
 * @since 2024-11-06
 */
@Service
@Slf4j
public class StockStorageServiceImpl extends ServiceImpl<StockStorageMapper, StockStorage> implements StockStorageService {

    @Autowired
    private StockStorageMapper stockStorageMapper;

    @Autowired
    private StockStorageHistoryMapper stockStorageHistoryMapper;

    @Autowired
    private RedisManager redisManager;

    @Override
    public int addStock(String classId, Integer count) {
        if (StringUtils.isEmpty(classId) || null == count) {
            throw new BusinessException(ResponseCode.PARAM_EXCEPTION);
        }
        //程序执行到这里 说明参数无误
        //如何添加库存呢? +1
        //首先去查询这个库存表中是否已经有记录了...
        QueryWrapper<StockStorage> stockStorageQuery = new QueryWrapper<>();
        stockStorageQuery.eq("class_id", classId);
        StockStorage stockStorage = stockStorageMapper.selectOne(stockStorageQuery);
        if (null != stockStorage) {
            //说明数据库中已经存在这条记录了...
            //说明这个不是第一次添加库存了...
            return manyAddClassStock(stockStorage, count).intValue();
        } else {
            //这里是第一次添加库存信息
            firstAddClassStock(classId, count);
            return count;
        }
    }

    /**
     * 这个方法还要加分布式锁...
     * @param queueMessage
     */
    @Override
    public void reduce(String queueMessage) {
        //首先将这个消息格式化成队列消息
        QueueMessage queueMessage1=JSON.parseObject(queueMessage, QueueMessage.class);
        //取出这个消息
        String message = queueMessage1.getMessage();
        //然后将这个消息格式化成想要的对象
        ReduceStock reduceStock = JSON.parseObject(message, ReduceStock.class);
        //然后取出消息
        Integer count = reduceStock.getCount();
        String orderNumber = reduceStock.getOrderNumber();
        //接下来：就可以通过订单号去查询这个课程id
        String orderMessage = redisManager.getString(orderNumber);
        //接下来就可以玩了
        if(StringUtils.isEmpty(orderMessage)){
            //说明这个订单号有误
            throw new BusinessException(ResponseCode.ORDER_NUMBER_EXCEPTION);
        }
        //执行到这里说明订单信息无误
        OrderShow orderShow = JSON.parseObject(orderMessage, OrderShow.class);
        String classId = orderShow.getClassId();
        log.info("减库存的这个商品id是:{}",classId);
        //接下来开始减库存
        //首先通过classId查询到库存信息
        QueryWrapper<StockStorage> stockStorageQueryWrapper = new QueryWrapper<>();
        stockStorageQueryWrapper.eq("class_id",classId);
        StockStorage stockStorage = stockStorageMapper.selectOne(stockStorageQueryWrapper);
        //接下来取出这个库存id
        //向库存历史表中写入一条记录
        StockStorageHistory stockStorageHistory = new StockStorageHistory();
        stockStorageHistory.setOutQuanty(count);
        stockStorageHistory.setInQuanty(0);
        stockStorageHistory.setStockStorageId(stockStorage.getStorageId());
        stockStorageHistoryMapper.insert(stockStorageHistory);
        //接下来：计算这个真实的库存
        Long countRealStock= stockStorageHistoryMapper.countStock(stockStorage.getStorageId());
        //然后去更新库存表中的真实库存
        stockStorage.setQuanty(countRealStock.intValue());
        //接下来更新数据
        stockStorageMapper.updateById(stockStorage);
    }

    /**
     * 多次添加库存之后的处理
     *
     * @param stockStorage
     */
    public Long manyAddClassStock(StockStorage stockStorage, Integer count) {
        //首先向库存历史表中添加一条记录
        StockStorageHistory stockStorageHistory = new StockStorageHistory();
        stockStorageHistory.setStockStorageId(stockStorage.getStorageId());
        stockStorageHistory.setInQuanty(count);
        stockStorageHistory.setOutQuanty(0);
        stockStorageHistoryMapper.insert(stockStorageHistory);
        //然后再计算这个实际库存有多少
        Long realCount = stockStorageHistoryMapper.countStock(stockStorage.getStorageId());
        //接下来再去更新这个库存表中的库存
        stockStorage.setQuanty(realCount.intValue());
        //更新这个库存信息
        stockStorageMapper.updateById(stockStorage);
        return realCount;
    }

    /**
     * 第一次添加库存
     *
     * @param classId
     * @param count
     */
    public void firstAddClassStock(String classId, Integer count) {
        //说明数据库中是第一次添加这个商品
        //先向库存表中添加1条记录
        StockStorage stockStorage1 = new StockStorage();
        stockStorage1.setClassId(classId);
        stockStorage1.setQuanty(count);
        stockStorage1.setWareHourseId("1");
        //向数据库中插入数据
        stockStorageMapper.insert(stockStorage1);
        //接下来再向库存历史表中添加一条记录
        StockStorageHistory stockStorageHistory = new StockStorageHistory();
        stockStorageHistory.setStockStorageId(stockStorage1.getStorageId());
        stockStorageHistory.setInQuanty(count);
        stockStorageHistory.setOutQuanty(0);
        stockStorageHistoryMapper.insert(stockStorageHistory);
    }
}
